package com.mxdx.edu.controller;

import com.alibaba.fastjson.JSONObject;
import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.AppException;
import com.mxdx.edu.common.CommonUtils;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.enums.ErrorEnums;
import com.mxdx.edu.enums.SubjectiveQuestionMarkEnums;
import com.mxdx.edu.model.ExamStudentRecord;
import com.mxdx.edu.model.StudentScore;
import com.mxdx.edu.service.IExamLibraryService;
import com.mxdx.edu.service.ISemesterService;
import com.mxdx.edu.service.IStudentService;
import com.mxdx.edu.util.RedisUtil;
import com.mxdx.edu.util.ServletUtil;
import com.mxdx.edu.util.SessionUtil;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.util.*;

import org.springframework.beans.BeanUtils;

/**
 * @author: liujianlu
 * @Description: 我要考试
 * @Date: Created in 15:16 2018/6/28
 */
@Controller
@RequestMapping(value = "/exam")
public class ExamIndexController extends BaseController {

    private AppLogger logger = new AppLogger(ExamIndexController.class);

    @Resource
    protected SessionUtil sessionUtil;

    @Resource
    protected RedisUtil redisUtil;

    @Resource
    protected IStudentService studentService;

    @Resource
    protected ISemesterService semesterService;

    @Resource
    protected IExamLibraryService examLibraryService;

    /**
     * 考试首页
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/auth/examIndex")
    public ModelAndView examIndex(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "examIndex");
        ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
        ModelAndView result = new ModelAndView("/h5/examIndex");
        List<Map<String, Object>> semesteList = new ArrayList<>();
        String studentName = "";
        String headPortrait = "";
        String mood = "";
        //String semesterName = "";
        //String semesterId = "";
        try {
            Map<String, Object> userMap = getStudentMap(request);
            String studentId = CommonUtils.getStrValueFromMap(userMap, "studentId", "");
            headPortrait = CommonUtils.getStrValueFromMap(userMap, "headPortrait", "");
            studentName = CommonUtils.getStrValueFromMap(userMap, "studentName", "");
            mood = CommonUtils.getStrValueFromMap(userMap, "mood", "");

            //通过学生id查询学生信息
            Map<String, Object> findStudentMap = new HashMap<>();
            findStudentMap.put("studentId", studentId);
            Map<String, Object> studentMap = studentService.findStudentMapOneByMap(findStudentMap);
            String classId = CommonUtils.getStrValueFromMap(studentMap, "classId", "");
            //课程信息
            semesteList = semesterService.findScoreListByMap(classId,studentId);
            //semesterName = CommonUtils.getStrValueFromMap(semesteList.get(0), "semesterName", "");
            //semesterId = CommonUtils.getStrValueFromMap(semesteList.get(0), "id", "");
            logger.info(ServletUtil.getClientIp(request));
        } catch (Exception e) {
            super.dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        result.addObject("courseList", semesteList);
        result.addObject("studentName", studentName);
        result.addObject("headPortrait", headPortrait);
        result.addObject("mood", mood);
        //result.addObject("semesterName", semesterName);
        //result.addObject("semesterId", semesterId);

        return result;
    }

    /**
     * 试题详情
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/auth/examDetail")
    public ModelAndView electionDetail(HttpServletRequest request) {
        logger.entry(ServletUtil.getClientIp(request), "examDetail");

        ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
        //判断是单选还是多选 返回页面  默认返回多选页面
        ModelAndView result = new ModelAndView("/h5/examDetail");

        Map<String,Object> userMap = getStudentMap(request);
        String studentId = CommonUtils.getStrValueFromMap(userMap,"studentId","");
        apiResult.setSerialNum(studentId);
        String courseId = ServletUtil.getParameterStr(request, "courseId", "");
        String semesterId = ServletUtil.getParameterStr(request, "semesterId", "");
        String examStatus = ServletUtil.getParameterStr(request, "examStatus", "0");
        String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");

        Map<String, Object> examTitleMap = new HashMap<>();
        List<Map<String, Object>> examSubjectList = new ArrayList<>();
        List<Map<String, Object>> examMainList = new ArrayList<>();
        List<Map<String, Object>> examOptionList = new ArrayList<>();
        List<Map<String, Object>> examAnswerList = new ArrayList<>();
        List<Map<String, Object>> examExplainList = new ArrayList<>();
        List<Map<String, Object>> retList = new ArrayList<>();

        int alreadyCount = 0;

        double examScoreSum = 0;
        //用于前台记录已做未做
        String testIds = "";
        try {

            //courseId = "694942e3b96a4f5bac3a42cd77de6eff";
            examTitleMap = examLibraryService.findExamTitleByCourseId(courseId);

            String examId = CommonUtils.getStrValueFromMap(examTitleMap, "id", "");

            examSubjectList = examLibraryService.findExamSubjectByExamId(examId);
            examMainList = examLibraryService.findExamMainByExamId(studentId,courseId,semesterId,examId);

            StudentScore studentScore = examLibraryService.findStudentScoreByMap(studentId,courseId,semesterId);

            if (studentScore != null){
                examScoreSum = studentScore.getExamScore();
                if("0".equals(exceedTerm)){
                    examStatus = String.valueOf(studentScore.getExamStatus());
                }

                if ("2".equals(examStatus)){
                    alreadyCount = examLibraryService.findExamStudentCountByMap(studentId,courseId,examId);
                    testIds = examLibraryService.findExamStudentTestIdsByMap(studentId,courseId,examId);
                }
            }

            List<String> testIdList = new ArrayList<>();
            for (Map<String, Object> testIdMap : examMainList) {

                testIdList.add(CommonUtils.getStrValueFromMap(testIdMap, "test_id", ""));
            }

            examOptionList = examLibraryService.findExamOptionByTestId(testIdList);
            examAnswerList = examLibraryService.findExamAnswerByTestId(testIdList);
            examExplainList = examLibraryService.findExamExplainByTestId(testIdList);

            //组装小题
            for (Map<String, Object> examMainMap : examMainList) {
                String testId = CommonUtils.getStrValueFromMap(examMainMap, "test_id", "");
                //获取选项
                List<Map<String, Object>> tempExamOptionList = new ArrayList<>();
                for (Map<String, Object> examOptionMap : examOptionList) {
                    String tempTestId = CommonUtils.getStrValueFromMap(examOptionMap, "test_id", "");
                    if (testId.equals(tempTestId)) {
                        tempExamOptionList.add(examOptionMap);
                    }
                }
                examMainMap.put("examOption", tempExamOptionList);

                //获取答案
                List<Map<String, Object>> tempExamAnswerList = new ArrayList<>();
                for (Map<String, Object> examAnswerMap : examAnswerList) {
                    String tempTestId = CommonUtils.getStrValueFromMap(examAnswerMap, "test_id", "");
                    if (testId.equals(tempTestId)) {
                        tempExamAnswerList.add(examAnswerMap);
                    }
                }
                examMainMap.put("examAnswer", tempExamAnswerList);

                //获取详解
                Map<String, Object> tempExamExplain = new HashMap<>();
                for (Map<String, Object> examExplainMap : examExplainList) {
                    String tempTestId = CommonUtils.getStrValueFromMap(examExplainMap, "test_id", "");
                    if (testId.equals(tempTestId)) {
                        tempExamExplain = examExplainMap;
                        break;
                    }
                }
                examMainMap.put("examExplain", tempExamExplain);
            }

            //组装大题
            for (Map<String, Object> examSubjectMap : examSubjectList) {
                String examStId = CommonUtils.getStrValueFromMap(examSubjectMap, "id", "");
                //获取小题
                for (Map<String, Object> examMainMap : examMainList) {
                    String tempExamStId = CommonUtils.getStrValueFromMap(examMainMap, "exam_st_id", "");
                    if (examStId.equals(tempExamStId)) {
                        Map<String, Object> temp = new HashMap<>();
                        temp.putAll(examSubjectMap);
                        temp.put("examMain", examMainMap);
                        retList.add(temp);
                    }
                }
            }

            logger.info(apiResult);
        } catch (Exception ex) {
            logger.doError(String.format("%s考试获取错误",studentId), ex);
            super.dealException(ErrorEnums.SYSTEM_ERROR, ex, apiResult, logger);
        }
        result.addObject("examTitleMap", examTitleMap);
        result.addObject("examSubjectList", retList);
        result.addObject("courseId", courseId);
        result.addObject("semesterId", semesterId);
        result.addObject("remainTest", examMainList.size());
        result.addObject("imageHost", imageHost);
        result.addObject("examStatus", examStatus);
        result.addObject("alreadyCount",alreadyCount);
        result.addObject("surplusCount",(examMainList.size() - alreadyCount));
        result.addObject("sumNum",examMainList.size());
        result.addObject("examScore",examScoreSum);
        result.addObject("exceedTerm",exceedTerm);
        result.addObject("testIds",testIds);

        return result;
    }

    /**
     * 答题
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/auth/examDetail/answer")
    @ResponseBody
    public ApiResult<String> answer(HttpServletRequest request,
                                                 HttpServletResponse response) {
        logger.entry(ServletUtil.getClientIp(request), "answer");
        ApiResult<String> result = new ApiResult<>();

        String courseId = ServletUtil.getParameterStr(request, "courseId", "");
        String semesterId = ServletUtil.getParameterStr(request, "semesterId", "");
        String examId = ServletUtil.getParameterStr(request, "examId", "");
        String examStId = ServletUtil.getParameterStr(request, "examStId", "");
        String testId = ServletUtil.getParameterStr(request, "testId", "");
        String answerIds = ServletUtil.getParameterStr(request, "answerIds", "");
        String answerText = ServletUtil.getParameterStr(request, "answerText", "");
        String answerImg = ServletUtil.getParameterStr(request, "answerImg", "");
        String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");
        try {

            Map<String, Object> userMap = getStudentMap(request);
            if(userMap == null){
                throw new AppException(ErrorEnums.LOGIN_TIME_ERROR.getCode(), ErrorEnums.LOGIN_TIME_ERROR.getDesc());
            }
            String studentId = CommonUtils.getStrValueFromMap(userMap, "studentId", "");
            result.setSerialNum(studentId);
            examLibraryService.examStudentDelete(studentId, courseId, examId, testId);
            ExamStudentRecord examStudentRecord = new ExamStudentRecord();
            examStudentRecord.setId(serialService.generateSerialNum("", 8));
            examStudentRecord.setStudentId(studentId);
            examStudentRecord.setCourseId(courseId);
            examStudentRecord.setSemesterId(semesterId);
            examStudentRecord.setExamId(examId);
            examStudentRecord.setExamStId(examStId);
            examStudentRecord.setTestId(testId);
            examStudentRecord.setAnswerIds(answerIds);
            examStudentRecord.setAnswerText(answerText);
            examStudentRecord.setAnswerImg(answerImg);
            examStudentRecord.setAnswerIds(answerIds);
            examStudentRecord.setRetest(Integer.parseInt(exceedTerm));
            examLibraryService.examStudentSave(examStudentRecord);
            logger.info(result);
        } catch (AppException e) {
            result.setStatus(e.getErrorCode());
            result.setMessage(e.getMessage());
            logger.info(result);
        }catch (Exception e) {
            super.dealException(ErrorEnums.SYSTEM_ERROR, e, result, logger);
            result.setStatus(ErrorEnums.SYSTEM_ERROR.getCode());
            result.setMessage(ErrorEnums.SYSTEM_ERROR.getDesc());
        }
        return result;
    }

    /**
     * 保存
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/auth/examDetail/save")
    @ResponseBody
    @Transactional(readOnly = false)
    public ApiResult<String> save(HttpServletRequest request,
                                               HttpServletResponse response) {
        logger.entry(ServletUtil.getClientIp(request), "answer");
        ApiResult<String> result = new ApiResult<>();

        String courseId = ServletUtil.getParameterStr(request, "courseId", "");
        String semesterId = ServletUtil.getParameterStr(request, "semesterId", "");
        String examId = ServletUtil.getParameterStr(request, "examId", "");
        String examTimeLimit = ServletUtil.getParameterStr(request,"minuteShow","0");
        String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");

        try {

            Map<String, Object> userMap = getStudentMap(request);
            String studentId = CommonUtils.getStrValueFromMap(userMap, "studentId", "");

            List<ExamStudentRecord> examStudentRecordList = examLibraryService.findExamStudentRecordByMap(studentId, courseId, examId);
            double score = examLibraryService.findNotSubjectiveScore(examId);
            double examScoreSum = 0;

            for (ExamStudentRecord examStudentRecord : examStudentRecordList) {

                List<String> testIdList = new ArrayList<>();
                testIdList.add(examStudentRecord.getTestId());

                List<Map<String, Object>> examAnswerList = examLibraryService.findExamAnswerByTestId(testIdList);

                List<Integer> testAnswerIdList = new ArrayList<>();
                for (Map<String, Object> testAnswerMap : examAnswerList) {

                    testAnswerIdList.add(Integer.parseInt(CommonUtils.getStrValueFromMap(testAnswerMap, "test_answer_id", "")));
                }

                Integer[] testAnswerIds = new Integer[testAnswerIdList.size()];

                testAnswerIdList.toArray(testAnswerIds);

                String[] answerId = examStudentRecord.getAnswerIds().split(",");

                Integer[] answerIdss = new Integer[answerId.length];

                for (int i = 0; i < answerId.length; i++) {
                    answerIdss[i] = Integer.parseInt(answerId[i]);
                }

                boolean correctStatus = Arrays.equals(testAnswerIds, answerIdss);

                if (correctStatus) {
                    examStudentRecord.setCorrectStatus(1);

                    Map<String, Object> examScoreMap = examLibraryService.findExamMainTestByMap(examStudentRecord.getTestId());

                    String examScore = CommonUtils.getStrValueFromMap(examScoreMap, "exam_score", "0");

                    examStudentRecord.setTestScore(Double.parseDouble(examScore));

                    examScoreSum += Double.parseDouble(examScore);

                } else {
                    examStudentRecord.setCorrectStatus(2);
                }
                examLibraryService.examStudentUpdate(examStudentRecord);
            }
            //硬性修改分数
            if(examScoreSum>score){
                examScoreSum = score;
            }
            //修改成绩
            StudentScore studentScore = examLibraryService.findStudentScoreByMap(studentId,courseId,semesterId);

            if (studentScore == null || studentScore.getId().length() < 1){
                StudentScore studentScore1 = new StudentScore();

                studentScore1.setId(serialService.generateSerialNum("", 8));
                studentScore1.setStudentId(studentId);
                studentScore1.setCourseId(courseId);
                studentScore1.setSemesterId(semesterId);
                studentScore1.setExamScore(examScoreSum);
                studentScore1.setExamTime(Integer.parseInt(examTimeLimit));
                studentScore1.setRetest(Integer.parseInt(exceedTerm));

                studentScore1.setExamStatus(2);
                //if (examScoreSum < 60){
                //    studentScore1.setExamStatus(3);
                //}

                examLibraryService.studentScoreSave(studentScore1);
            }else {
                studentScore.setExamScore(examScoreSum);
                studentScore.setExamTime(Integer.parseInt(examTimeLimit));
                studentScore.setExamStatus(2);
                if (studentScore.getRetest() != 1) {
                    studentScore.setRetest(Integer.parseInt(exceedTerm));
                }
                //if (examScoreSum < 60){
                //    studentScore.setExamStatus(3);
                //}

                examLibraryService.studentScoreUpdate(studentScore);
            }
            result.setInfo(String.valueOf(examScoreSum));
        } catch (Exception e) {
            super.dealException(ErrorEnums.SYSTEM_ERROR, e, result, logger);
            result.setStatus(ErrorEnums.SYSTEM_ERROR.getCode());
            result.setMessage(ErrorEnums.SYSTEM_ERROR.getDesc());
        }

        return result;
    }

}
